package com.xpgk.common.controller;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Config;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Redis;
import com.xpgk.common.kit.CacheKitEx;
import com.xpgk.common.kit.PubKit;
import com.xpgk.xpsoft.constants.XPSoftConstant;

public class BaseController extends Controller {
	

	public void renderJSONMsg(String msg, boolean bSuccess) {
		setAttr("result", bSuccess ? 1 : 0);
		setAttr("msg", msg);
		renderJson();
	}

	public void renderMsg(String errorMessage, String view) {
		setAttr("result", 0);
		setAttr("msg", errorMessage);
		render(view);
	}

	public void renderMsg(String msg, String view, boolean bSuccess) {
		setAttr("result", bSuccess ? 1 : 0);
		setAttr("msg", msg);
		render(view);
	}

	public boolean requiredString(String field, String errorMessage) {
		if (StrKit.isBlank(getPara(field))) {
			setAttr("result", 0);
			setAttr("msg", errorMessage);
			return true;
		}
		return false;
	}

	public int SetCurUser(String userName, int userID) {
		setSessionAttr("userID", userID);
		setSessionAttr("userName", userName);
		return 0;
	}

	public int getCurUserID() {
		return PubKit.ifNull((Integer) getSessionAttr("userID"), -1);
	}

	public String getCurUserName() {
		return getSessionAttr("userName");
	}

	public Record GetRecord(String recordName) {
		Record record = new Record();
		String modelNameAndDot = StrKit.notBlank(recordName) ? recordName + "." : null;
		Map<String, String[]> parasMap = getParaMap();
		for (Entry<String, String[]> entry : parasMap.entrySet()) {
			String paraName = entry.getKey();
			String attrName;
			if (modelNameAndDot != null) {
				if (paraName.startsWith(modelNameAndDot)) {
					attrName = paraName.substring(modelNameAndDot.length());
				} else {
					continue;
				}
			} else {
				attrName = paraName;
			}

			String[] paraValueArray = entry.getValue();
			String paraValue = (paraValueArray != null && paraValueArray.length > 0) ? paraValueArray[0] : null;
			paraValue = (paraValue != null && paraValue.length() > 0) ? paraValue : null;

			record.set(attrName, paraValue);
		}
		return record;
	}

	/**
	 * Keep all parameter's value include model value
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Controller keepPara() {
		Map<String, Map> m = new HashMap<>();
		HttpServletRequest request = getRequest();
		Map<String, String[]> map = getRequest().getParameterMap();
		for (Entry<String, String[]> e : map.entrySet()) {
			String[] values = e.getValue();
			if (values.length == 1) {
				if (e.getKey().indexOf(".") >= 0) {
					String key = e.getKey().substring(0, e.getKey().indexOf("."));
					Map mm = m.get(key);
					if (mm == null) {
						mm = new HashMap<>();
						m.put(key, mm);
						request.setAttribute(key, mm);
					}
					mm.put(e.getKey().substring(e.getKey().indexOf(".") + 1), values[0]);
				} else
					request.setAttribute(e.getKey(), values[0]);
			} else
				request.setAttribute(e.getKey(), values);
		}
		return this;
	}

	@Override
	public Controller setSessionAttr(String key, Object value) {
		// TODO Auto-generated method stub
		if (CacheKitEx.IsUseRedis()) // 在redis中共享session
		{
			String sessionid = getCookie("sessionid");
			if (sessionid == null) {
				sessionid = super.getSession(true).getId();
				setCookie("sessionid", sessionid, -1, true);
			}
			Redis.use(XPSoftConstant.cacheName).hset("sessionid" + sessionid, key, value);
			Redis.use(XPSoftConstant.cacheName).expire("sessionid" + sessionid, 1200);
			return this;
		}
		return super.setSessionAttr(key, value);
	}

	@Override
	public <T> T getSessionAttr(String key) {
		// TODO Auto-generated method stub
		if (CacheKitEx.IsUseRedis())// 在redis中共享session
		{
			String sessionid = getCookie("sessionid");
			if (sessionid == null) {
				return null;
			}
			Redis.use(XPSoftConstant.cacheName).expire("sessionid" + sessionid, 1200);
			return Redis.use(XPSoftConstant.cacheName).hget("sessionid" + sessionid, key);
		}
		return super.getSessionAttr(key);
	}

	@Override
	public HttpSession getSession(boolean create) {
		// TODO Auto-generated method stub

		if (CacheKitEx.IsUseRedis())
			return null;
		return super.getSession(create);
	}

	// @Override
	public HttpSession getSession() {
		// TODO Auto-generated method stub
		// return super.getSession();
		if (CacheKitEx.IsUseRedis())
			return null;
		// throw new Exception("do not use this function,use getSessionAttr or
		// setSessionAttr.");
		return super.getSession();
	}

	public String getSessionID() {
		if (CacheKitEx.IsUseRedis())
			return getCookie("sessionid");
		// throw new Exception("do not use this function,use getSessionAttr or
		// setSessionAttr.");
		return super.getSession().getId();
	}

	protected void rollback() {
		Config config = DbKit.getConfig();

		Connection conn = config.getThreadLocalConnection();
		if (conn != null) { // Nested transaction support
			try {
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	protected void commit() {
		Config config = DbKit.getConfig();

		Connection conn = config.getThreadLocalConnection();
		if (conn != null) { // Nested transaction support
			try {
				conn.commit();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 分页查询
	 * 
	 * @param sqlId
	 * @param para
	 * @return
	 */
	protected String paging(String sqlId, Kv para) {
		int page = getParaToInt("page", 1);
		int limit = getParaToInt("limit", 10);
		Page<Record> pages = Db.paginate(page, limit, Db.getSqlPara(sqlId, para));
		String json = JsonKit.toJson(pages.getList());
		json = "{\"code\":0,\"msg\":\"\",\"count\":" + pages.getTotalRow() + ",\"data\":" + json + "}";
		return json;
	}
	
	
}
